// Infrastructure/Repositories/SystemConfigRepository.cs
using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Domain.Entities;
using UniversalAdmin.Domain.Repositories;
using UniversalAdmin.Infrastructure.Data;

namespace UniversalAdmin.Infrastructure.Repositories;

public class SystemConfigRepository : BaseRepository<SystemConfig>, ISystemConfigRepository
{
  public SystemConfigRepository(UniversalAdminDbContext context) : base(context) { }

  public async Task<SystemConfig?> GetByKeyAsync(string key)
  {
    return await _context.SystemConfigs
        .FirstOrDefaultAsync(c => c.Key == key);
  }

  public async Task<string?> GetValueByKeyAsync(string key, string? defaultValue = null)
  {
    var config = await GetByKeyAsync(key);
    return config?.Value ?? defaultValue;
  }

  public async Task SetValueByKeyAsync(string key, string value)
  {
    var config = await GetByKeyAsync(key);
    if (config == null)
    {
      config = new SystemConfig { Key = key, Value = value };
      await _context.SystemConfigs.AddAsync(config);
    }
    else
    {
      config.Value = value;
    }

    await _context.SaveChangesAsync();
  }

  public async Task<IEnumerable<SystemConfig>> GetByKeysAsync(IEnumerable<string> keys)
  {
    return await _context.SystemConfigs
        .Where(c => keys.Contains(c.Key))
        .ToListAsync();
  }

  public async Task<IEnumerable<SystemConfig>> GetByIdsAsync(IEnumerable<int> ids)
  {
    return await _context.SystemConfigs
        .Where(c => ids.Contains(c.Id))
        .ToListAsync();
  }

  public async Task UpdateMultipleAsync(IEnumerable<SystemConfig> configs)
  {
    _context.SystemConfigs.UpdateRange(configs);
    await _context.SaveChangesAsync();
  }
}